package com.gzsxy.esjy.common.base.util;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @description: jwt生成工具
 * @author zxl
 * @since 2022/3/5
 */
public class JwtUtils {

    private static final Logger log = LoggerFactory.getLogger(JwtUtils.class);

    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    //返回key是你的byte数组定义的密钥，SecretKeySpec是采用某种加密算法加密后的密钥
    private static Key getKeyInstance(){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //将Base64编码后的String还原成字节数组
        byte[] bytes = DatatypeConverter.parseBase64Binary(APP_SECRET);
        //用于构建秘密密钥规范
        return new SecretKeySpec(bytes,signatureAlgorithm.getJcaName());
    }

    public static String getJwtToken(JwtInfo jwtInfo, int expire){

        String JwtToken = Jwts.builder()
                //定义JWT头信息（指定签名使用的算法）
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //有效载荷部分
                //主题
                .setSubject("esjy-user")
                //颁发时间
                .setIssuedAt(new Date())
                //过期时间 plusSeconds增加时间
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                //用户id
                .claim("id", jwtInfo.getId())
                //用户昵称
                .claim("nickname", jwtInfo.getName())
                //用户头像
                .claim("avatar", jwtInfo.getImagePath())
                //签名哈希
                .signWith(SignatureAlgorithm.HS256, getKeyInstance())
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkJwtTToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkJwtTToken(ServerHttpRequest request) {
        try {
            String jwtToken = request.getHeaders().getFirst("Authorization");
            if(StringUtils.isEmpty(jwtToken)) {
                return false;
            }
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    public static JwtInfo getMemberIdByJwtToken(ServerHttpRequest request) {

        String jwtToken = request.getHeaders().getFirst("Authorization");
        if(StringUtils.isEmpty(jwtToken)) {
            return null;
        }
        log.info("【获取当前用户jwt-token为】{}",jwtToken);
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        JwtInfo jwtInfo = new JwtInfo(claims.get("id").toString(), claims.get("nickname").toString(), claims.get("avatar").toString());
        log.info("【解析用户信息】:{}", JSON.toJSONString(jwtInfo));
        return jwtInfo;
    }

    public static JwtInfo getMemberIdByJwtToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) {
            return null;
        }
        log.info("【获取当前用户jwt-token为】{}",jwtToken);
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        JwtInfo jwtInfo = new JwtInfo(claims.get("id").toString(), claims.get("nickname").toString(), claims.get("avatar").toString());
        log.info("【解析用户信息】:{}", JSON.toJSONString(jwtInfo));
        return jwtInfo;
    }


    public static void main(String[] args) {
        String jwtToken  = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJlc2p5LXVzZXIiLCJpYXQiOjE2NTEzODU0NDQsImV4cCI6MTY1MTM4NzI0NCwiaWQiOiIxNDU1NDcwNjIzNzEyNjQ5MjE3Iiwibmlja25hbWUiOiJhZG1pbiIsImF2YXRhciI6ImZpcnN0LWZpbGUtc2VydmVyLzIwMjIwMjA5MTYxNzUzNGFlMTUwMzQxNDNhNDBhMmI5YjMyYmZiN2FlZjc4NWIuanBnIn0.zcZ48zz_316NF7jF8vKos0fVMX0WPNSGPzFYTYdaS88";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        JwtInfo jwtInfo = new JwtInfo(claims.get("id").toString(), claims.get("nickname").toString(), claims.get("avatar").toString());
        log.info("【解析用户信息】:{}", JSON.toJSONString(jwtInfo));
    }
}
